package com.kim.rssreader.activity;

import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndFeed;
import com.kim.rssreader.R;
import com.kim.rssreader.utils.ActivityDispatchUtil;
import com.kim.rssreader.utils.ImgFilter;
import com.kim.rssreader.utils.NetUtil;
import com.kim.rssreader.utils.RssSourceReader;
import com.kim.rssreader.utils.Utils;
import com.kim.rssreader.utils.ValueConstant;

public class RssContentViewActivity extends BaseActivity implements
		View.OnClickListener, OnTouchListener, OnGestureListener {

	public static final int ZOOM = 0x000001;
	public static final int DRAG = 0x000002;
	public static final int NONE = 0x000003;

	public static final int PRE = 0; // 上一篇
	public static final int NEXT = 1; // 下一篇

	public static final String TAG = "RssContentViewActivity";

	ImageView mBack; // 返回按钮
	ImageView mRefresh; // 刷新按钮

	WebView webView = null;

	String columnId = null;
	String title = null;
	String url = null;
	String content = null;
	String time = null;
	SyndFeed feed = null;
	DownloadRssContentFeedTask downloadRssFeedTask = null;

	List<SyndEntry> entriesLocal = null;

	GestureDetector gestureDetector;

	private String columnFlagStarter = null;
	private String columnFlagEnd = null;

	int mode = -1;

	float newDist = -1;
	float oldDist = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (content != null) {
			refreshPage(content);
		} else {
			downloadRssFeedTask = new DownloadRssContentFeedTask();
			downloadRssFeedTask.execute();
		}
	}

	@Override
	public void initParam() {
		Intent intent = getIntent();
		if (intent != null) {
			url = intent.getStringExtra("url");
			title = intent.getStringExtra("title");
			time = intent.getStringExtra("time");
			columnFlagStarter = intent.getStringExtra("flagStart");
			columnFlagEnd = intent.getStringExtra("flagEnd");
			content = intent.getStringExtra("content");
			columnId = intent.getStringExtra("columnId");
			entriesLocal = dbDAO.getColumnItemByColumnId(columnId);
		}
	}

	public void initView() {

		setContentView(R.layout.rss_content_view);

		gestureDetector = new GestureDetector(this);

		mBack = (ImageView) findViewById(R.id.iv_back);
		mBack.setOnClickListener(this);

		mRefresh = (ImageView) findViewById(R.id.iv_refresh);
		mRefresh.setOnClickListener(this);

		webView = (WebView) findViewById(R.id.view_rsscontent);
		webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webView.getSettings().setJavaScriptEnabled(true);

		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				webView.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}
		});
		webView.getSettings().setDefaultTextEncodingName(
				RssSourceReader.ENCODING);
		webView.getSettings().setSupportZoom(false);
		webView.setOnTouchListener(this);
	}

	@Override
	protected void onDestroy() {
		if (downloadRssFeedTask != null) {
			downloadRssFeedTask.isShutdown = true;
		}
		super.onDestroy();
	}

	private class DownloadRssContentFeedTask extends
			AsyncTask<Void, Void, String> {

		boolean isShutdown = false;

		@Override
		protected void onPreExecute() {
			startRefreshAnim();
		}

		@Override
		protected String doInBackground(Void... params) {
			String content = null;
			try {
				content = Utils.fetchData(url);
				content = Utils.interceptedContent(content, columnFlagStarter,
						columnFlagEnd);
				return content;
			} catch (Exception e) {
				Log.e("RssContentViewActivity", e.getMessage(), e);
			} finally {
			}
			return null;
		}

		@Override
		protected void onPostExecute(final String content) {
			// hide the progress indicator when the network request is complete
			stopRefreshAnim();
			refreshPage(content);
			new Thread(new Runnable() {

				@Override
				public void run() {
					dbDAO.updateRSSContent(content, url);
				}
			}).start();
		}

	}

	public void refreshPage(String content) {

		if (downloadRssFeedTask != null && downloadRssFeedTask.isShutdown) {
			return;
		}
		if (content == null) {
			webView.loadData("No Rss Content loaded.", "text/html", "utf-8");
			return;
		}

		// 过滤内容页中的图片地址
		// content = ImgFliter.fliter(content);

		// 网络可用且内容不为空，则不使用cache
		if (NetUtil.isNetAvailable(this)) {
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		} else {
			webView.getSettings().setCacheMode(
					WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}
		webView.loadDataWithBaseURL("",
				Utils.buildContent(this, url, content, title, time),
				"text/html", "utf-8", "");
	}

	/**
	 * 开始刷新动画
	 */
	private void startRefreshAnim() {
		Log.i(TAG, "start animation");
		Animation animation = AnimationUtils.loadAnimation(this,
				R.anim.refresh_anim);
		mRefresh.setAnimation(animation);
		animation.start();
	}

	/**
	 * 结束刷新动画
	 */
	private void stopRefreshAnim() {
		Log.i(TAG, "stop animation");
		Animation animation = mRefresh.getAnimation();
		if (animation != null) {
			animation.cancel();
			animation = null;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.iv_refresh:
			if (content == null) {
				if (downloadRssFeedTask == null) {
					downloadRssFeedTask = new DownloadRssContentFeedTask();
					downloadRssFeedTask.execute();
				}
			} else {
				refreshPage(content);
			}
			break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case /* MotionEvent.ACTION_POINTER_DOWN */261: // 多点触控
			mode = ZOOM;
			oldDist = spacing(event);
			break;
		case /* MotionEvent.ACTION_POINTER_UP */262:
			mode = NONE;
			break;
		case MotionEvent.ACTION_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == ZOOM) {
				newDist = spacing(event);
				if (newDist / oldDist > 1) {
					// webView.zoomIn();
					System.out.println("zoomIn");
				} else {
					// webView.zoomOut();
					System.out.println("zoomOut");
				}
			}
			break;
		}
		return false;
	}

	private float spacing(MotionEvent event) {
		try {
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return FloatMath.sqrt(x * x + y * y);
		} catch (Exception e) {
			Log.d("ScaleDragableTouchListener",
					"java.lang.IllegalArgumentException:pointerIndex out of range");
		}
		return 0;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (gestureDetector.onTouchEvent(ev)) {
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		float distanceX = Math.abs(e2.getX() - e1.getX());
		float distanceY = Math.abs(e2.getY() - e1.getY());

		if (distanceX < ValueConstant.FLINGDISTANCE || distanceX < distanceY) {
			// 限制滑动角度，当 distanceX < distanceY时
			// ，就证明角度太大，可以归并为是垂直滑动不是水平滑动
			return false;
		}

		int dirctFlag = -1;

		if (velocityX > ValueConstant.VELOCITY_X) { // 左滑
			dirctFlag = PRE;
		} else if (velocityX < -ValueConstant.VELOCITY_X) { // 右滑
			dirctFlag = NEXT;
		}

		SyndEntry syndEntry = getTargetContent(url, dirctFlag);

		if (syndEntry == null) {
			if (dirctFlag == PRE) {
				Utils.toastShort(RssContentViewActivity.this,
						R.string.message_no_pre);
			} else if (dirctFlag == NEXT) {
				Utils.toastShort(RssContentViewActivity.this,
						R.string.message_no_next);
			}
			return true;
		}

		ActivityDispatchUtil.toContentPage(RssContentViewActivity.this,
				syndEntry, null, columnFlagStarter, columnFlagEnd, columnId);

		// 销毁当前页
		RssContentViewActivity.this.finish();

		// 设置动画
		if (dirctFlag == PRE) {
			overridePendingTransition(R.anim.slide_left_in,
					R.anim.slide_right_out);
		} else if (dirctFlag == NEXT) {
			overridePendingTransition(R.anim.slide_right_in,
					R.anim.slide_left_out);
		}

		return false;
	}

	/**
	 * 获取目标内容
	 * 
	 * @param currentUrl
	 * @param dirctFlag
	 * @return
	 */
	private SyndEntry getTargetContent(String currentUrl, int dirctFlag) {

		if (entriesLocal == null || entriesLocal.size() == 0) {
			return null;
		}

		int index = -1;
		for (SyndEntry entry : entriesLocal) {
			index++;
			if (currentUrl.equals(entry.getLink())) {
				if (PRE == dirctFlag) {
					index--;
				} else if (NEXT == dirctFlag) {
					index++;
				}
				if (index < 0 || index >= entriesLocal.size()) {
					return null;
				}
				return entriesLocal.get(index);
			}
		}
		return null;
	}

}
